import React, { Component } from 'react';
import { Button, Card, Modal, message, Table } from "antd"
import { RoleGet, UserAdd, UserGet, UserUpdate, UserDelete } from "../../../api/index"
import AddUser from "./AddUser"
import MyButton from "../../../components/button/MyButton"
const { confirm } = Modal;

class user extends Component {
    constructor(props) {
        super(props)
        this.adduser = React.createRef()
    }




    state = {
        roleList: [],
        resetVisible: false,
        users: [], //储存所有用户的数组
        loading: true,
        user: {}, //储存单个用户的对象
        isUpdate: false,  //判断是否是修改用户信息的操作
        _id: null,  //储存当前修改用户的_id
    }

    componentDidMount() {
        this.getData();
    }

    // 添加角色窗口添加取消按钮触发的事件
    handlerCanel = () => {
        this.setState({
            resetVisible: false
        })
        this.form.props.form.resetFields()
    }

    // 添加角色窗口添加确认按钮触发的事件
    handlerOk = () => {
        this.form.props.form.validateFields(async (err, values) => {
            const { isUpdate } = this.state
            let result = null;
            if (isUpdate) {
                values._id = this.state._id;
                result = await UserUpdate(values);
            } else {
                result = await UserAdd(values);
            }
            const { status, msg } = result;
            if (status) {
                message.success(msg)
                this.setState({
                    resetVisible: false
                })
                this.form.props.form.resetFields()
                this.getData();
            } else {
                message.error(msg)
            }
        })


    }

    // 点击添加用户按钮触发的事件
    handleruser = () => {
        this.setState({
            resetVisible: true,
            user: {},
            isUpdate: false
        })
    }



    // 获取用户和角色
    getData = async () => {
        const result = await Promise.all([RoleGet(), UserGet()])
        const roleList = result[0]
        const users = result[1].users
        this.setState({
            roleList,
            users,
            loading: false
        })
    }

    // 修改用户
    undateuser = (user) => {
        this.setState({
            resetVisible: true,
            user,
            isUpdate: true,
            _id: user._id
        })
    }
    // 点击删除按钮执行的操作
    handlerdelete = (user) => {
        confirm({
            title: '信息提醒',
            content: `确定删除用户“${user.userName}”吗？`,
            okText: "确认",
            cancelText: "取消",
            centered: true,
            onOk: () => {
                this.deleteuser(user)
            },
            onCancel() {
                
            },
        });
        
    }
    // 删除用户
    deleteuser = async (user) => {
        const result = await UserDelete(user);
        const { status, msg } = result;
        if (status) {
            message.success(msg)
            this.getData();
        } else {
            message.error(msg)
        }
    }

    render() {

        const { roleList, users, loading, user, isUpdate } = this.state;

        const columns = [
            {
                title: '用户名',
                dataIndex: 'userName',
                key: 'userName',
            },
            {
                title: '用户密码',
                dataIndex: 'passWord',
                key: 'passWord',
            },
            {
                title: '手机号码',
                dataIndex: 'phone',
                key: 'phone',
            },
            {
                title: '所属角色',
                dataIndex: 'userGrade',
                key: 'userGrade',
                render: (userGrade) => {
                    let role = roleList.find(item => {
                        return item._id === userGrade
                    })
                    return role.roleName;
                }
            },
            {
                title: '创建时间',
                dataIndex: 'createTime',
                key: 'createTime',
                render: (createTime) => {
                    return new Date(createTime).toLocaleString()
                }
            },
            {
                title: '执行操作',
                key: "operation",
                render: (user) => (
                    <span>
                        <MyButton style={{ marginRight: 20 }} onClick={() => { this.undateuser(user) }}>修改</MyButton>
                        <MyButton onClick={() => { this.handlerdelete(user) }}>删除</MyButton>
                    </span>
                )
            }
        ];

        const title = (
            <span>
                <Button type="primary" icon="plus" onClick={this.handleruser}>添加用户</Button>
            </span>
        )
        return (
            <div>
                <Card title={title} style={{ borderBottom: "none" }}>
                    <Table
                        dataSource={users}  //数据源
                        columns={columns} //每列的信息
                        rowKey="_id"
                        bordered
                        loading={loading}
                        pagination={{ defaultPageSize: 4 }}

                    />

                    <Modal
                        title={isUpdate ? "修改用户信息" : "添加用户"}
                        visible={this.state.resetVisible}
                        onOk={this.handlerOk}
                        onCancel={this.handlerCanel}
                        okText="确认"
                        cancelText="取消"
                    >
                        <AddUser
                            wrappedComponentRef={(form) => this.form = form}
                            roleList={roleList}
                            user={user}
                            ref={this.adduser}
                        ></AddUser>
                    </Modal>
                </Card>
            </div>
        );
    }
}

export default user;